from PyQt5 import QtWidgets
from PyQt5.QtGui import QImage
from PyQt5.QtWidgets import QMessageBox, QListWidget, QHBoxLayout, QSplitter, QListWidgetItem, QCheckBox, QFileDialog
from PySide2.QtGui import QPixmap
from PySide2.QtUiTools import QUiLoader
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QListView, QMessageBox
import sys
from PySide2 import QtGui
from PySide2.QtWidgets import QLabel
import os, base64
import requests as req
from PIL import Image
from io import BytesIO
from login2_ui import Ui_MainWindow
import requests

# url = "http://172.19.138.187:10000/task"
url = "http://127.0.0.1:9000/upload"


class Window_main(Ui_MainWindow, QWidget):
    def __init__(self, *args, obj=None, **kwargs):
        super(Window_main, self).__init__(*args, **kwargs)

        self.ui2 = QUiLoader().load('login2.ui')
        self.ui2.label.clear()
        self.ui2.label_3.clear()
        self.ui2.label_2.clear()
        self.ui2.pushButton.clicked.connect(self.openimage)
        self.ui2.pushButton_2.clicked.connect(self.show)
        self.ui2.pushButton_3.clicked.connect(self.send)
        self.image = ""
        self.imgName = ""
        self.result = ""

    def openimage(self):
        # 显示图片
        self.ui2.label.setText("已上传选择图片")
        self.imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
        print(self.imgName)
        jpg = QtGui.QPixmap(self.imgName).scaled(self.ui2.label_2.width(), self.ui2.label_2.height())
        self.ui2.label_2.setPixmap(jpg)

    def send(self):  # flask发送
        self.ui2.label.setText("已发送")
        file_name = self.imgName.split('/')[-1]
        file = open(self.imgName, 'rb')
        files = {'file': (file_name, file)}
        r = requests.post(url, files=files)
        self.result = str(r.content,'utf-8')
        print(self.result)
        os.system('python ../Padim/test.py')
        self.ui2.label.setText("处理完成")

    def show(self):
        print(self.result)
        result_path = os.path.join(self.result,"big_0.png")
        print(result_path)
        jpg2 = QtGui.QPixmap(result_path).scaled(self.ui2.label_3.width(), self.ui2.label_2.height())
        self.ui2.label_3.setPixmap(jpg2)
        self.ui2.label.setText("正常显示结果")


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    myWin = Window_main()
    myWin.ui2.show()
    sys.exit(app.exec_())
